#include "stm32f10x.h"                  // Device header
#include "main.h"

void PWM_Init(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);  		//打开时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);		//初始化GPIOA
	
	GPIO_InitTypeDef GPIO_InitStructe;                     //中间变量
	GPIO_InitStructe.GPIO_Mode = GPIO_Mode_AF_PP;			//复用推挽，PWM通过引脚输出
	
	GPIO_InitStructe.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2|GPIO_Pin_3;	//PWM口
	GPIO_InitStructe.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructe);
	
	TIM_InternalClockConfig(TIM2);								//选择内部时钟
	
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;          //初始化时基单元(结构体变量)
	TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_Period = 100-1;				//ARR	1KHZ
	TIM_TimeBaseInitStructure.TIM_Prescaler = 36-1;			//PSC
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
	
	TIM_OCInitTypeDef TIM_OCInitStructure;
	TIM_OCStructInit(&TIM_OCInitStructure);						//给结构体变量赋值
	TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;	    	    //设置输出比较的模式
	TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;	   //设置输出比较的极性
	TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;  //设置输出使能
	TIM_OCInitStructure.TIM_Pulse=0;							   //CCR
	TIM_OC1Init(TIM2,&TIM_OCInitStructure);						//四个通道
	TIM_OC2Init(TIM2,&TIM_OCInitStructure);
	TIM_OC3Init(TIM2,&TIM_OCInitStructure);
	TIM_OC4Init(TIM2,&TIM_OCInitStructure);
	
//	TIM_ClearFlag(TIM2, TIM_FLAG_Update);
//	TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
	
//	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
//	
//	NVIC_InitTypeDef NVIC_InitStructure;
//	NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
//	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
//	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
//	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
//	NVIC_Init(&NVIC_InitStructure);
	
	TIM_Cmd(TIM2,ENABLE);										//启动定时器
	
}

void Speed_Set(uint16_t Compare)
{
	TIM_SetCompare1(TIM2,Compare);
	TIM_SetCompare2(TIM2,Compare);
	TIM_SetCompare3(TIM2,Compare);
	TIM_SetCompare4(TIM2,Compare);
}

//void TIM2_IRQHandler(void)
//{
//	if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
//	{
//		
//		TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
//	}
//}
